<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<script>
// 2023.7.21没参考任何人的代码，只有一个目的：自己写个promise——支持异步触发，支持链式调用
class myPromise {
    constructor(executor) {
        this.value = undefined;
        this.status = 'pending';

        this.onFullfilledCallbacks = [];
        this.onRejectedCallbacks = [];

        executor(this.resolve.bind(this), this.reject.bind(this));
    }

    resolve(value) {
        this.value = value;
        this.status = 'fullfilled';
        while(this.onFullfilledCallbacks.length !== 0) {
            const result = this.onFullfilledCallbacks.shift()();
        }
    }

    reject(value) {
        this.value = value;
        this.status = 'rejected';
        while(this.onRejectedCallbacks.length !== 0) {
            this.onRejectedCallbacks.shift()(this.value);
        }
    }

    then(onFullfilledCallback, onRejectedCallback) {
        const promise = new myPromise((resolve, reject) => {
            if(this.status === 'fullfilled') {
                const result = onFullfilledCallback(this.value);
                resolve(result);
                if(result instanceof myPromise) {
                    return result;
                }
            }
            if(this.status === 'rejected') {
                const result = onRejectedCallback(this.value);
                reject(result);
                if(result instanceof myPromise) {
                    return result;
                }
            }
            if(this.status === 'pending') {
                this.onFullfilledCallbacks.push(() => {
                    const result = onFullfilledCallback(this.value);
                    promise.resolve(result);
                    if(result instanceof myPromise) {
                        return result;
                    }
                });
                this.onRejectedCallbacks.push(onRejectedCallback);
            }
        })
        return promise;
    }
}

// 支持调用链中存在异步代码
const test = new myPromise((resolve) => {
    setTimeout(() => {
        resolve(1);
    }, 500);
})
    .then((res) => {
        console.log(res);
        return 2 * res;
    })
    .then((res) => {
        console.log(res);
    });
// 支持then中返回promise
const test2 = new myPromise((resolve) => {
    setTimeout(() => {
        resolve(1);
    }, 500);
})
    .then((res) => {
        return new myPromise((resolve) => {
            resolve(2 * res);
        })
    })
    .then((res) => {
        console.log("@@@", res);
    });
// 同步代码链式调用
const test3 = new myPromise((resolve) => {
    resolve(1);
})
    .then((res) => {
        console.log(res);
        return 2 * res;
    })
    .then((res) => {
        console.log(res);
    });
</script>
</body>
</html>